package com.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.common.constant.LoginConstant;
import com.common.to.MemberTo;
import com.common.to.OAuthResTo;
import com.common.to.UserLoginTo;
import com.common.utils.HttpUtils;
import com.common.utils.R;
import com.gulimall.auth.feign.MemberFeignService;
import com.gulimall.auth.vo.OAuthResVo;
import com.gulimall.auth.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-22 16:28
 */
@Controller
@Slf4j
public class LoginController {

    @Resource
    MemberFeignService memberFeignService;

    /**
     * 微博第三方登陆
     * @param code
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String oauth(@RequestParam String code, HttpSession session) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","2685970253");
        map.put("client_secret","f23e55c02a329c896b253d4603fbe1ce");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);
        // 1、发出请求获取 accessToken（请求参数code只能使用一次，而获取到的 accessToken 可以在有效时间内多次使用）
        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        // 2、处理结果
        if(httpResponse.getStatusLine().getStatusCode() == 200){
            String jsonString = EntityUtils.toString(httpResponse.getEntity()); // 获取到json串，不能使用JSON来转
            OAuthResVo oAuthResVo = JSON.parseObject(jsonString, OAuthResVo.class);
            OAuthResTo oAuthResTo = new OAuthResTo();
            oAuthResTo.setUid(oAuthResVo.getUid());
            oAuthResTo.setExpiresIn(oAuthResVo.getExpires_in());
            oAuthResTo.setRemindIn(oAuthResVo.getRemind_in());
            oAuthResTo.setAccessToken(oAuthResVo.getAccess_token());
            R r = memberFeignService.OAuth(oAuthResTo);
            if(r.getCode() == 0){
                MemberTo memberTo = r.getData(new TypeReference<MemberTo>() {});
                session.setAttribute(LoginConstant.LOGIN_USERNAME,memberTo);
                return "redirect:http://gulimall.com";
            }

        }
        // 登陆失败，直接返回登陆页面
        return "redirect:http://auth.gulimall.com/login.html";

    }

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes,HttpSession httpSession){
        HashMap<String, String> errorMap = new HashMap<>();
        UserLoginTo userLoginTo = new UserLoginTo();
        BeanUtils.copyProperties(userLoginVo,userLoginTo);
        R r = memberFeignService.login(userLoginTo);
        // 发生异常
        if(r.getCode() != 0){
            String msg = r.getData("msg", new TypeReference<String>() {});
            errorMap.put("msg",msg);
            redirectAttributes.addFlashAttribute("errors",errorMap);
            return "redirect:http://auth.gulimall.com/login.html";
        }
        // 登陆成功
        MemberTo memberTo = r.getData(new TypeReference<MemberTo>(){});
        httpSession.setAttribute(LoginConstant.LOGIN_USERNAME,memberTo);
        return "redirect:http://gulimall.com";
    }
}
